import { createApp } from 'vue'
import { createPinia } from 'pinia'

import ElementPlus, { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'

import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import App from './App.vue'
import router from './router'

import './assets/styles/base.css' // css 样式重置
// import './assets/styles/common.css' // 公共全局样式
import './assets/iconfont/iconfont.css' // 字体图标的样式

// import './assets/styles/index.css' // 页面样式

// axios请求拦截器(就是前端发出请求携带token)
axios.interceptors.request.use(config => {
  let token = window.sessionStorage.getItem('token')
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})

// axios响应拦截器
let isShowMsg = false  //规避多次弹出提示消息
axios.interceptors.response.use(res => {
  if (res.data && res.data.code == 401) {
    // 获取当前路由路径
    const currentPath = router.currentRoute.value.path;
    
    // 这些路径即使收到401响应也不做重定向，允许用户浏览
    const publicPaths = ['/', '/home', '/booksDetails', '/topicBlock'];
    
    // 检查当前路径是否是公开路径或以公开路径开头
    const isPublicPath = publicPaths.some(path => 
      currentPath === path || (path !== '/' && currentPath.startsWith(path + '/'))
    );
    
    // 如果不是公开路径，才执行重定向
    if (!isPublicPath && !isShowMsg) {
      isShowMsg = true   //已经提示
      ElMessage({
        message: '你还没有登录，请先登录',
        type: 'warning'
      })
      router.push('/login').finally(() => {
        isShowMsg = false
      })
    }
    return res  // 确保返回响应
  } else {
    return res
  }
}, err => {
  console.log('请求错误：' + err.message);
  return Promise.reject(err)
})

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.use(ElementPlus)
app.mount('#app')

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
